/**
 * Handler used to organize log messages into a graphical user interface
 *
 * @created Feb 3, 2007
 * @author jprieur
 */
package utils;

import java.util.logging.Logger;
import java.util.logging.Handler;
import java.util.logging.XMLFormatter;
import java.util.logging.LogRecord;
import java.util.HashMap;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Monitor extends Handler
{
    /** Formatter used to save log files from the monitoring tool */
    private static XMLFormatter _xml_formatter = new XMLFormatter();
    
    private GraphicalMonitor _gm;

    public Monitor()
    {
	_gm = new GraphicalMonitor();
    }

    // Methods inherited from Handler
    public void close()
    {}

    public void flush()
    {}

    public void publish(LogRecord record)
    {
	if(_gm != null) _gm.publish(record);
    }
    
    public static void main(String[] args)
    {
	new Monitor();
    }

    // GUI stuff
    public class GraphicalMonitor extends JFrame
    {
	private HashMap<String, LoggerPanel> _panels;
	private JTabbedPane _tabs;
	
	public GraphicalMonitor()
	{
	    super("SimMobil logging tool");
	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    setSize(600, 400);

	    _panels = new HashMap<String, LoggerPanel>();

	    _tabs = new JTabbedPane(JTabbedPane.TOP,
				    JTabbedPane.SCROLL_TAB_LAYOUT);
	    
	    for(int i = 0;i < Debug.getLoggers().length;i++){
		String current = Debug.getLoggers()[i].getName();
		_panels.put(current, new LoggerPanel());
		_tabs.add(current, new LoggerPanel());
	    }

	    setLayout(new BorderLayout());
	    add("Center", _tabs);

	    setVisible(true);
	}
	
	public void publish(LogRecord record)
	{
	    String logger = record.getLoggerName();
	    _panels.get(logger).publish(record);
	}
    }

    public class LoggerPanel extends JPanel
    {
	private JTextArea _text;

	public LoggerPanel()
	{
	    _text = new JTextArea();
	    setLayout(new BorderLayout());
	    add("Center", new JScrollPane(_text,
					  JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
					  JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
	}
    
	public void publish(LogRecord record)
	{
	    System.out.println("Record to publish :" + record.getMessage());
	    _text.append("\n" + record.getMessage());
	}

    }
}